<template>
  <el-card class="page_card">
    <el-tabs v-model="activeName">
      <el-tab-pane label="系统配置" name="first">
        <el-form :model="data.systemForm" ref="formRef" label-width="100px" style="max-width: 500px;margin-top: 20px;">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="data.systemForm.projectName" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="logo" prop="file">
          <el-upload
            class="avatar_uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleChange">
            <img v-if="data.fileImg" :src="data.fileImg" class="avatar" />
            <el-icon v-else class="avatar_uploader_icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" color="#626aef" @click="onSubmit">保存</el-button>
        </el-form-item>
      </el-form>
      </el-tab-pane>
      <el-tab-pane label="关于我们" name="second">
        <div style="border: 1px solid #dcdfe6;margin-bottom: 14px;">
          <Toolbar style="border-bottom: 1px solid #dcdfe6" :editor="editorRef" 
            :defaultConfig="toolbarConfig" mode="default"/>
          <Editor style="height: 500px; overflow-y: hidden" v-model="valueHtml" class="editor_con"
            :defaultConfig="editorConfig" mode="default" @onCreated="editorInit"/>
        </div>
        <el-button type="primary" color="#626aef" @click="onSubmitEditor">保存</el-button>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import {reqGetDictByParentCode,reqAddOrUpdateDict,reqSetLogo,reqGetLogo} from '@/api/sys/dictApi'
import { reqGetImg,uploadFile } from '@/api/file/index'
import { blobToUrl } from '@/utils/file'
import { ElMessage } from "element-plus"
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { onBeforeUnmount, shallowRef } from 'vue'

let data = reactive({
  systemForm:{
    projectName:'',
    file:'',
    id:'',
    version:'',
  },
  fileImg:'', //上传图片后回显
  aboutUsObj:{
    id:'',
    version:'',
    richText:'',
  }
})
const activeName = ref('first')

// 富文本编辑器
const editorRef = shallowRef()
const valueHtml = ref('')
// 工具栏和编辑栏 配置
const toolbarConfig = {
  //excludeKeys: []
  insertKeys: {
    index: 21, // 自定义插入的位置
    keys: ['uploadAttachment'], // “上传附件”菜单
  }
}
const editorConfig = { 
  placeholder: '请输入内容...',
  hoverbarKeys: {
    attachment: {
      menuKeys: ['downloadAttachment'], // “下载附件”菜单
    },
  },
  MENU_CONF: {
    uploadImage: {
      // 小于该值就插入 base64 格式（而不上传），默认为 0
      base64LimitSize: 5 * 1024, // 5kb
      // 单个文件的最大体积限制，默认为 2M
      // maxFileSize: 1 * 1024 * 1024, // 1M
      // // 最多可上传几个文件，默认为 100
      // maxNumberOfFiles: 5,
      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ['image/*'],
      async customUpload(file:any, insertFn:any) { // 文件上传
        try {
            const formData = new FormData();
            formData.append('file', file);
            let res= await uploadFile(formData);
            
            if (res) {
              insertFn(`/api/file/preview/${res}`,file.name,file.name);
            }else{
              ElMessage.error("图片上传失败");
            }
            
        } catch (e) {
          ElMessage.error("图片上传失败");
        }
         // 插入到富文本编辑器中，主意这里的三个参数都是必填的，要不然控制台报错：typeError: Cannot read properties of undefined (reading 'replace')
        // insertFn(result.data.data.url, result.data.data.name, result.data.data.name)
      }
    },
    uploadVideo:{
      async customUpload(file:any, insertFn:any) {
        try {
          const formData = new FormData();
          formData.append('file', file);
          let res= await uploadFile(formData);
          if (res) {
            insertFn(`/api/file/preview/${res}`,file.name,file.name);
          }else{
            ElMessage.error("视频上传失败");
          } 
        } catch (e) {
          ElMessage.error("视频上传失败");
        }
      }
    },
    uploadAttachment: {
      async customUpload(file: File, insertFn: Function) {
        let formData = new FormData();
        formData.append("file", file);
        let res= await uploadFile(formData);
        if (res) {
          insertFn(file.name,`/api/file/preview/${res}`);
        }else{
          ElMessage.error("附件上传失败");
          return;
        }
	    }
    }
  }
}
// 编辑器初始化完成时的回调函数
const editorInit = (editor:any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

onMounted(() => {
  initLogoImg()
  initProjectName()
  initAboutUs()
})

// 保存关于我们字典值aboutUsRichText
const onSubmitEditor = async () => {
  if(!valueHtml.value) {
    ElMessage.error('请输入内容！')
    return false
  }
  let params = {
    id:data.aboutUsObj.id,
    parentCode:'00000', //00000默认根节点
    dictName:'aboutUsRichText', //字典名
    dictValue:valueHtml.value, //字典值
    version:data.aboutUsObj.version
  }
  let res = await reqAddOrUpdateDict(params)
  if(res.code==200){
    ElMessage.success('保存成功！')
    initAboutUs()
  }
}
const initAboutUs = async () => {
  // 查询项目名称字典值
  let res = await reqGetDictByParentCode('00000')
  if(res.code==200){
    let tempRes = res.data.find((item:any) => item.dictName=='aboutUsRichText')
    if(tempRes){
      data.aboutUsObj = res.data.find((item:any) => item.dictName=='aboutUsRichText')
      valueHtml.value = res.data.find((item:any) => item.dictName=='aboutUsRichText').dictValue
    }
  }
}

// 保存项目名称字典值projectName
const onSubmit = async () => {
  if(!data.systemForm.projectName) {
    ElMessage.error('请输入项目名称！')
    return false
  }
  let params = {
    id:data.systemForm.id,
    parentCode:'00000', //00000默认根节点
    dictName:'projectName', //字典名
    dictValue:data.systemForm.projectName, //字典值
    version:data.systemForm.version
  }
  let res = await reqAddOrUpdateDict(params)
  if(res.code==200){
    ElMessage.success('保存成功！')
    initProjectName()
  }
}
const initProjectName = async () => {
  // 查询项目名称字典值
  let res = await reqGetDictByParentCode('00000')
  if(res.code==200){
    let tempRes = res.data.find((item:any) => item.dictName=='projectName')
    if(tempRes){
      data.systemForm = res.data.find((item:any) => item.dictName=='projectName')
      data.systemForm.projectName = res.data.find((item:any) => item.dictName=='projectName').dictValue
    }
  }
}

const initLogoImg = async () => {
  let imgNameRes = await reqGetLogo()
  if(imgNameRes.code==200){
    // 根据文件名获取图片数据回显img
    let imgRes = await reqGetImg(imgNameRes.data)
    if (imgRes) {
      // blob转url
      blobToUrl(imgRes).then(dataUrl => {  
        data.fileImg = dataUrl
      }).catch(error => {
        ElMessage.error(error)
      })
    }
  }
}

// 图片上传
const handleChange = async (file:any) => {
  // data.systemForm.file = file.raw //FormData格式图片
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = (e) => {
    data.fileImg = (e.target?.result as string)
  }
  
  const formData = new FormData()
  formData.append('file', file.raw) //上传文件处理
  let res = await reqSetLogo(formData)
  if(res.code==200){
    ElMessage.success('上传成功！')
  }
}
</script>

<style scoped lang="scss">
.avatar_uploader .avatar {
  width: 200px;
  // height: 120px;
  display: block;
}
:deep(.el-tabs__item.is-active) {
  color: #626aef;
}
:deep(.el-tabs__item:hover) {
  color: #626aef;
}
:deep(.el-tabs__active-bar) {
  background-color: #626aef;
}
</style>

<style>
.avatar_uploader .el-upload {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar_uploader .el-upload:hover {
  border-color: #626aef;
}
.el-icon.avatar_uploader_icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px !important;
  /* height: 120px !important; */
  text-align: center;
}
.editor_con{
  strong {
    font-weight: bold !important;
  }
  em {
    font-style: italic !important;
  }
}
</style>